<template>
  <div :class="{'editMode':isEdit}" class="dynamic-table-container">
    <div class="top">
      <div class="flex">
        <div><Title title="分摊费用" /></div>
        <div class="data-container">
          <div class="data-item">
            <img :src="incomeAmountIcon" alt="">
            <div class="label">总分摊金额：</div>
            <div v-if="(totalPrice || totalPrice===0)" class="num">{{ moneyFilter((totalPrice), true, '', true) }}</div>
            <div v-else>--</div>
          </div>
        </div>
      </div>
      <PlainCreateBtn v-if="isEdit" @click="addItem">添加</PlainCreateBtn>
    </div>
    <el-table
      v-if="(list && list.length)"
      ref="dynamicEditRef"
      :data="list"
      :border="true"
      fit
      element-loading-text="加载中..."
      header-cell-class-name="dynamic-edit-table-cell"
    >
      <!--  :align="settingItem.type === 'number' && !isEdit?'right':'left'" -->
      <el-table-column v-for="(settingItem,index) in cellData" :key="index" :label="settingItem.label" :min-width="settingItem.minWidth" align="left">
        <template slot="header" slot-scope="scope">
          <!-- :class="{'right': settingItem.type === 'number' && !isEdit}" -->
          <div class="dynamic-table-header"><span v-if="isEdit" class="required">*</span><span class="label">{{ scope.column.label }}</span></div>
        </template>
        <template slot-scope="scope">
          <div v-if="isEdit" :class="{'isError': errorIds.includes(`${settingItem.keyword}-${scope.$index}`) && isEdit}" class="edit-area">
            <el-cascader
              v-if="settingItem.type === 'dept'"
              v-model="scope.row[settingItem.keyword]"
              :show-all-levels="false"
              :options="deptTreeList"
              :props="{emitPath:false,value: 'id',label: 'name',checkStrictly: true,multiple: false}"
              :ref="`cascader-${scope.$index}`"
              filterable
              class="department-all"
              size="small"
              placeholder="请选择部门"
              clearable
              @change="deptChange($event, scope.row, `cascader-${scope.$index}`)"
            >
              <template slot-scope="{ data }">
                <ToolTip :content="data.name" />
              </template>
            </el-cascader>
            <el-input
              v-if="settingItem.type === 'text'"
              v-model="scope.row[settingItem.keyword]"
              :maxlength="500"
              :placeholder="settingItem.placeholder || settingItem.label"
              size="small"
              type="text"
              class="edit-table-input-text"
              clearable
              @change="removeError"
            />
            <el-input
              v-if="settingItem.type === 'number'"
              v-model="scope.row[settingItem.keyword]"
              :placeholder="settingItem.placeholder || settingItem.label"
              :oninput="`if(value>${settingItem.maxnumber || 999999999}) {value=${settingItem.maxnumber || 999999999}}else if(${settingItem.isPositiveNumber} && value < 0) {value = null}`"
              type="number"
              size="small"
              @change="numberInputChange(scope.row, settingItem.keyword)"
              @mousewheel.native.prevent
            />
          </div>
          <div v-else class="flex-block">
            <ToolTip v-if="settingItem.type === 'text'" :content="scope.row[settingItem.keyword]" />
            <ToolTip v-if="settingItem.type === 'dept'" :content="scope.row.departmentName" />
            <PriceColumn v-if="settingItem.type==='number'" :real-val="scope.row[settingItem.keyword]" :price="scope.row[settingItem.keyword]" />
            <div v-if="isEditEvent && settingItem.keyword === 'remark'" class="button-text edit-remark-btn" @click="openDialog(scope.row, scope.$index)">编辑</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="isEdit" :width="100" align="left" label="操作" fixed="right">
        <template slot-scope="scope">
          <div style="padding: 0 10px;">
            <el-button :disabled="list.length === 1" type="text" @click="deleteItem(scope.$index)"><span style="font-size:14px;">删除</span></el-button>
            <el-button type="text" @click="copyItem(scope.row)"><span style="font-size:14px;">复制</span></el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <empty-placeholder v-else :empty-img="emptyDataIcon" empty-text="暂无数据" image-size="100px" style="margin-bottom: 24px" />
    <!-- 编辑结算单名称和备注 -->
    <el-dialog v-if="isEditEvent" :class="{'mobile-page-dialog':showMobilePage}" :visible.sync="dialogEditVisible" :close-on-click-modal="false" class="small-common-dialog-size" @close="closeDialog">
      <Title title="编辑说明" />
      <div class="edit-main">
        <el-input v-model="editRemark" :maxlength="500" size="small" placeholder="请输入分摊说明" type="text" />
      </div>
      <div class="edit-dialog-btn">
        <el-button type="primary" size="small" @click="edit()">保存</el-button>
        <el-button type="info" size="small" class="cancel-btn-style" @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Title from '@/components/Title';
import emptyDataIcon from '@/assets/empty-data-icon.png';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import { showModal } from '@/utils/message';
import { editAllocationRemark } from '@/api/supplier';
import math from '@/utils/math';
import { mapState } from 'vuex';

import { moneyFilter } from '@/filters/number';
import { getDepartmentAll } from '@/api/config';
import incomeAmountIcon from '@/assets/chargeOffDetail/incomeAmount.png';
export default {
  name: 'AllocationAmount',
  components: { Title, EmptyPlaceholder },
  model: {
    prop: 'list',
    event: 'changeData'
  },
  props: {
    list: {
      type: Array,
      default: () => {
        return [];
      }
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    isEditEvent: {
      type: Boolean,
      default: false
    },
    examinId: {
      type: Number | String,
      default: ''
    }
  },
  data() {
    return {
      incomeAmountIcon, emptyDataIcon,
      dialogEditVisible: false,
      editRemark: '',
      editRemarkIndex: 0,
      deptTreeList: [],
      errorIds: [],
      cellData: [
        { label: '分摊部门', keyword: 'departmentId', minWidth: 80, type: 'dept' },
        { label: '分摊金额(元)', keyword: 'amount', minWidth: 80, type: 'number' },
        { label: '分摊说明', keyword: 'remark', type: 'text' }
      ]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    totalPrice() {
      let price;
      this.list.forEach(i => {
        if (i.amount || i.amount === 0) {
          price = math.add(price || 0, Number(i.amount));
          // price = (price || 0) + Number(i.amount);
        }
      });
      return price;
    }
  },
  created() {
    this.queryDeptTreeList();
  },
  methods: {
    moneyFilter,
    deptChange(id, item, ref) {
      this.$nextTick(() => {
        if (this.$refs[ref] && this.$refs[ref][0]) {
          const node = this.$refs[ref][0].getCheckedNodes()[0] || null;
          if (node && node.value === id) item.departmentName = node.label || '';
        }
      });
      this.removeError();
    },
    validate() {
      return new Promise((resolve, reject) => {
        let isOk = true;
        const errorIds = [];
        this.list.forEach((i, index) => {
          if (!i.departmentId) {
            errorIds.push(`departmentId-${index}`);
            isOk = false;
          }
          if (!i.amount && i.amount !== 0) {
            errorIds.push(`amount-${index}`);
            isOk = false;
          }
          if (!i.remark) {
            errorIds.push(`remark-${index}`);
            isOk = false;
          }
        });
        this.errorIds = errorIds;
        if (isOk) {
          resolve(true);
        } else {
          reject(false);
        }
      });
    },
    removeError() {
      this.errorIds = [];
    },
    addItem() {
      this.list.push({
        // departmentName: '',
        departmentId: '',
        amount: '',
        remark: ''
      });
      this.changeData();
    },
    copyItem(item) {
      const copy = _.cloneDeep(item);
      this.list.push(copy);
      this.changeData();
    },
    deleteItem(index) {
      showModal('是否确定删除？', '', {
        center: true,
        showClose: true
      }).then(() => {
        this.list.splice(index, 1);
        this.changeData();
      });
    },
    changeData() {
      this.$emit('changeData', this.list);
      this.removeError();
    },
    numberInputChange(row, key) {
      if (row[key]) row[key] = Number(row[key]).toFixed(2);
      this.changeData();
    },
    queryDeptTreeList(sort = false) {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
        // if (sort) cascaderSoft(this.paramsObj.cooperationDepartment, this.deptTreeList);
      }).catch(e => {
        console.log(e);
      });
    },
    closeDialog() {
      this.dialogEditVisible = false;
      this.editRemark = '';
      this.editRemarkIndex = 0;
    },
    openDialog(item, index) {
      this.dialogEditVisible = true;
      this.editRemark = item.remark;
      this.editRemarkIndex = index;
    },
    edit() {
      const editRemark = this.editRemark;
      if (!editRemark) {
        this.$message.error('请输入分摊说明');
        return;
      }
      const index = this.editRemarkIndex;
      const remarks = this.list.map(i => {
        return i.remark;
      });
      remarks[index] = editRemark;
      const params = {
        id: this.examinId,
        remarks
      };
      editAllocationRemark(params).then(res => {
        if (res.code === 200) {
          this.$emit('getInfo', this.examinId);
          this.closeDialog();
          this.$message.success('修改成功');
        } else {
          this.$message.error(res.message);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.top {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
  .flex {
    display: flex;
    align-items: center;
    flex: 1;
  }
}
.flex-block {
  display: flex;
  align-items: center;
}
.edit-remark-btn {
  margin-left: 4px;
  flex-shrink: 0;
}
.edit-main {
  margin: 16px 0;
}
.edit-dialog-btn {
  display: flex;
  align-items: center;
  justify-content: center;
}
.required {
  color: #f56c6c;
  margin-right:4px;
}
.department-all {
  width: 100%;
}
.mobile-page-dialog {
  &::v-deep {
    .el-dialog {
      width: 76% !important;
    }
  }
}
.data-container {
  background: #fafafc;
  border-radius: 4px;
  padding: 0px 12px;
  margin-left: 10px;
  .data-item {
    display: flex;
    align-items: center;
    min-width: 200px;
    height: 30px;
    img {
      width: 16px;
      margin-right: 5px;
    }
    .label {
      font-size: 14px;
      line-height: 14px;
      color: #999;
    }
    .num {
      font-size: 16px;
      font-family: DIN Alternate, DIN Alternate-Bold;
      font-weight: 700;
      color: #5f77c3;
    }
  }
}
.dynamic-table-container {
  margin-top: 24px;
  .dynamic-table-header {
    display:flex;align-items:center;
    .label {
      color: #141C3D;
      font-weight: 600;
    }
    &.right {
      justify-content: flex-end;
    }
  }
  &::v-deep {
    .el-table__body tr > td {
      background-color: #fff !important;
    }
    .el-cascader-menu__wrap {
      height: unset !important;
      max-height: 204px !important;
    }
    .dynamic-edit-table-cell {
      background: #F9F9F9;
    }
    .el-table__fixed {
      &::before {
        background-color: transparent;
      }
    }
    .el-table__fixed-right {
      &::before {
        background-color: transparent;
      }
    }
    .el-table--border::after {
      background-color: transparent;
    }
    .el-table {
      border-color: transparent;
      &::before {
        background-color: transparent;
      }
      // .el-table__body-wrapper {
      //   padding-bottom: 7px;
      // }
      thead {
        th.dynamic-edit-table-cell {
          &:last-child {
            border-right-color: transparent;
          }
          &:nth-last-child(2) {
            border-right-color: transparent;
          }
        }
      }
      .is-scrolling-none {
        .el-table__empty-block {
          width: 100% !important;
        }
      }
      .el-table__empty-text {
        width: 100%;
      }
      tbody {
        tr {
          td:last-child {
            border-right-color: transparent;
          }
        }
        .el-table__row {
          &:last-child {
            td {
              border-bottom: 1px solid #EBEEF5;
            }
          }
        }
      }
    }
    .el-date-table,.el-year-table,.el-month-table {
      th {
        border-right: none;
      }
    }
    .el-date-table td {
      padding: 4px 0 !important; border: none !important;
    }
    .el-year-table td {
      padding: 20px 3px !important; border: none !important;
    }
    .el-month-table td {
      padding: 8px 0 !important; border: none !important;
    }
  }
  &.editMode {
    &::v-deep {
      .el-select__caret {
        color: #333;
      }
      .el-table__row {
        td {
          padding: 0;
        }
        .cell {
          padding: 0;
          .el-input__inner {
            height: 56px;
            border-radius: 0;
            border-color: transparent;
          }
        }
      }
    }
  }
}
.isError {
  &::v-deep {
    .el-input__inner {
      border-color: red !important;
    }
  }
}
</style>
